package net.mayee.common;

import jodd.log.Logger;
import jodd.log.LoggerFactory;
import net.mayee.alice.entity.menu.NavbarMenus;
import net.mayee.alice.entity.menu.SidebarMenus;
import net.mayee.alice.entity.menu.nanbar.Logo;
import net.mayee.alice.entity.menu.nanbar.Logout;
import net.mayee.alice.entity.menu.nanbar.NavbarMenu;
import net.mayee.alice.entity.menu.nanbar.Profile;
import net.mayee.alice.entity.menu.sidebar.SidebarMenu;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MenuHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(MenuHelper.class);
    private String version;
    private SidebarMenus sidebarMenus = new SidebarMenus();
    private NavbarMenus navbarMenus = new NavbarMenus();

    private SidebarMenu activeSidebarMenu;
    private SidebarMenu activeSidebarSubMenu;
    private NavbarMenu activeNavbarMenu;

    private String activeHref;
    private String activeSbuHref;
    private String MENU_URL_PREFIX;

    {
        activeHref = "";
        activeSbuHref = "";
        MENU_URL_PREFIX = "";
    }

    private MenuHelper() {
        initMenuHelper();
    }

    private static final MenuHelper menuHelper = new MenuHelper();

    public static MenuHelper getInstance() {
        return menuHelper;
    }

    private void initMenuHelper() {
        MENU_URL_PREFIX = AliceHelper.getInstance().getJoddProps().getValue("menu.url.prefix");
        loadMenuXml();
    }

    public String getVersion() {
        return version;
    }

    public SidebarMenus getSidebarMenus() {
        return sidebarMenus;
    }

    public NavbarMenus getNavbarMenus() {
        return navbarMenus;
    }

    public NavbarMenu getActiveNavbarMenu() {
        return activeNavbarMenu;
    }

    private void setActiveNavbarMenu(NavbarMenu activeNavbarMenu) {
        this.activeNavbarMenu = activeNavbarMenu;
    }

    public SidebarMenu getActiveSidebarMenu() {
        return activeSidebarMenu;
    }

    private void setActiveSidebarMenu(SidebarMenu activeSidebarMenu) {
        this.activeSidebarMenu = activeSidebarMenu;
    }

    public SidebarMenu getActiveSidebarSubMenu() {
        return activeSidebarSubMenu;
    }

    private void setActiveSidebarSubMenu(SidebarMenu activeSidebarSubMenu) {
        this.activeSidebarSubMenu = activeSidebarSubMenu;
    }

    public String getMenuName(String menuId) {
        List<SidebarMenu> sbmList = sidebarMenus.getSidebarMenu();
        for (SidebarMenu sbm : sbmList) {
            if (sbm.getId().equals(menuId)) {
                return sbm.getName();
            }
            List<SidebarMenu> subMenuList = sbm.getSubMenuList();
            for (SidebarMenu sub_sbm : subMenuList) {
                if (sub_sbm.getId().equals(menuId)) {
                    return sub_sbm.getName();
                }
            }
        }
        return null;
    }

    /**
     * 打印时已active属性为准，但在判断时必须检查active属性+(setActiveSidebarMenu/setActiveSidebarSubMenu)
     *
     * @param href
     */
    public void buildActiveSidebarMenu(String href) {
//        System.out.println("in setActiveSidebarMenu");
//        System.out.println("activeHref-bef:" + activeHref + "    activeSbuHref-bef:" + activeSbuHref);
        if (href.equals(this.activeHref) || href.equals(this.activeSbuHref))
            return;
//        System.out.println("do setActiveSidebarMenu");
        List<SidebarMenu> sidebarMenuList = sidebarMenus.getSidebarMenu();
        for (SidebarMenu sbm : sidebarMenuList) {
            if (sbm.isHadSubMenu()) {
                boolean isNotFind = true;
                List<SidebarMenu> subList = sbm.getSubMenuList();
                for (SidebarMenu sbm_sub : subList) {
                    if (sbm_sub.getHref().equals(href)) {
                        sbm_sub.setActive(true);
                        sbm.setActive(true);
                        isNotFind = false;

                        this.activeHref = sbm.getHref();
                        this.activeSbuHref = sbm_sub.getHref();

                        this.setActiveSidebarMenu(sbm);
                        this.setActiveSidebarSubMenu(sbm_sub);
                    } else {
                        sbm_sub.setActive(false);
                    }
                }
                if (isNotFind) {
                    sbm.setActive(false);
                }

            } else {
                /**
                 * 没有子菜单的情况
                 */

                /* href */
                String sbm_menu_href = sbm.getHref();
                if (href.equals(sbm_menu_href)) {
                    sbm.setActive(true);
                    this.setActiveSidebarMenu(sbm);
                } else {
                    sbm.setActive(false);
                }

                this.activeHref = sbm_menu_href;
                this.activeSbuHref = "";
            }
        }
//        System.out.println("activeHref-aft:" + activeHref + "    activeSbuHref-aft:" + activeSbuHref);
    }

    private void loadMenuXml() {
        String xmlPath = AliceHelper.getInstance().getJoddProps().getValue("menu.xml.path");
        SAXReader reader = new SAXReader();
        Document document;
        try {
            InputStream in = this.getClass().getResourceAsStream(xmlPath);
            document = reader.read(in);
        } catch (Exception e) {
            LOGGER.error("**** MenuHelper -> loadMenuXml fail! ****", e);
            return;
        }

        /* reset */
        sidebarMenus = new SidebarMenus();
        navbarMenus = new NavbarMenus();
        
        /* 只有第一个active属性会生效 */
        boolean firstActive = true;

        Element root = document.getRootElement();
        for (Iterator iterA = root.elementIterator(); iterA.hasNext(); ) {
            // 获取节点 version/sidebarMenus/navbarMenus
            Element elementA = (Element) iterA.next();
            if (elementA != null && elementA.hasContent()) {
                if ("sidebarMenus".equals(elementA.getName())) {
                    // 获取节点 sidebarMenu
                    for (Iterator iterB = elementA.elementIterator(); iterB
                            .hasNext(); ) {
                        Element elementB = (Element) iterB.next();
                        if (elementB != null && "sidebarMenu".equals(elementB.getName())) {
                            Attribute attrB_id = elementB.attribute("id");
                            Attribute attrB_name = elementB.attribute("name");
                            Attribute attrB_messageKey = elementB.attribute("messageKey");

                            //create SidebarMenu(menu)
                            SidebarMenu sbm_menu = new SidebarMenu(
                                    attrB_id.getText(),
                                    attrB_name.getText(),
                                    attrB_messageKey.getText());

                            Attribute attrB_href = elementB.attribute("href");
                            if (attrB_href != null) {
                                sbm_menu.setHref(MENU_URL_PREFIX + attrB_href.getText());
                            }
                            Attribute attrB_icon = elementB.attribute("icon");
                            if (attrB_icon != null) {
                                sbm_menu.setIcon(attrB_icon.getText());
                            }
                            Attribute attrB_active = elementB.attribute("active");
                            if (firstActive && attrB_active != null && "true".equalsIgnoreCase(attrB_active.getText())) {
                                sbm_menu.setActive(true);
                                this.activeHref = MENU_URL_PREFIX + (attrB_href != null ? attrB_href.getText() : "");
                                this.setActiveSidebarMenu(sbm_menu);
                                firstActive = false;
                            }

                            /* 只有不带HREF属性的父菜单，才会读取其子菜单 */
                            if (attrB_href == null && elementB.hasContent()) {
                                List<SidebarMenu> subMenuList = new ArrayList<SidebarMenu>();
                                // 获取节点 sidebarSubMenu
                                for (Iterator iterC = elementB.elementIterator(); iterC
                                        .hasNext(); ) {
                                    Element elementC = (Element) iterC.next();
                                    if (elementC != null) {

                                        Attribute attrC_id = elementC.attribute("id");
                                        Attribute attrC_name = elementC.attribute("name");
                                        Attribute attrC_messageKey = elementC.attribute("messageKey");

                                        //create SidebarMenu(sub-menu)
                                        SidebarMenu sbm_submenu = new SidebarMenu(
                                                attrC_id.getText(),
                                                attrC_name.getText(),
                                                attrC_messageKey.getText());

                                        Attribute attrC_icon = elementC.attribute("icon");
                                        if (attrC_icon != null) {
                                            sbm_submenu.setIcon(attrC_icon.getText());
                                        } else {
                                            sbm_submenu.setIcon(AliceHelper.getInstance().getJoddProps().getValue("menu.default.icon"));
                                        }

                                        Attribute attrC_href = elementC.attribute("href");
                                        if (attrC_href != null) {
                                            sbm_submenu.setHref(MENU_URL_PREFIX + attrC_href.getText());
                                        } else {
                                            sbm_submenu.setHref("");
                                        }
                                        sbm_submenu.setIsSubMenu(true);
                                        sbm_submenu.setParentSidebarMenu(sbm_menu);
                                        subMenuList.add(sbm_submenu);
                                    }
                                }//sidebarSubMenu end
                                sbm_menu.setSubMenuList(subMenuList);
                            }
                            sidebarMenus.getSidebarMenu().add(sbm_menu);
                        }
                    }// sidebarMenu end
                }// sidebarMenus end
                else if ("navbarMenus".equals(elementA.getName())) {
                    // 获取节点 logo/profile
                    for (Iterator iterB = elementA.elementIterator(); iterB
                            .hasNext(); ) {
                        Element elementB = (Element) iterB.next();
                        if (elementB != null) {
                            String elementB_name = elementB.getName();
                            if ("logo".equals(elementB_name)) {
                                Attribute attrB_href = elementB.attribute("href");
                                Attribute attrB_imgSrc = elementB.attribute("imgSrc");
                                Attribute attrB_alt = elementB.attribute("alt");
                                Logo logo = new Logo(MENU_URL_PREFIX + attrB_href.getText(), attrB_imgSrc.getText());
                                if (attrB_alt != null) {
                                    logo.setAlt(attrB_alt.getText());
                                } else {
                                    logo.setAlt("");
                                }
                                navbarMenus.setLogo(logo);
                            } else if ("profile".equals(elementB_name)) {
                                Attribute attrB_showPhoto = elementB.attribute("showPhoto");
                                Attribute attrB_viewName = elementB.attribute("viewName");
                                Profile profile = new Profile(
                                        attrB_showPhoto.getText(), attrB_viewName.getText());
                                navbarMenus.setProfile(profile);
                                
                                /* load navbarMenu */
                                if (elementB.hasContent()) {
                                    for (Iterator iterC = elementB.elementIterator(); iterC
                                            .hasNext(); ) {
                                        Element elementC = (Element) iterC.next();
                                        Attribute attrC_id = elementC.attribute("id");
                                        Attribute attrC_name = elementC.attribute("name");
                                        Attribute attrC_messageKey = elementC.attribute("messageKey");
                                        Attribute attrC_href = elementC.attribute("href");
                                        Attribute attrC_icon = elementC.attribute("icon");
                                        Attribute attrC_hadBottomLine = elementC.attribute("hadBottomLine");

                                        //create NavbarMenu
                                        NavbarMenu nbm_menu = new NavbarMenu(
                                                attrC_id.getText(),
                                                attrC_name.getText(),
                                                attrC_messageKey.getText(),
                                                MENU_URL_PREFIX + attrC_href.getText(),
                                                attrC_icon.getText());

                                        try {
                                            if (attrC_hadBottomLine != null) {
                                                nbm_menu.setHadBottomLine(Boolean.parseBoolean(attrC_hadBottomLine.getText()));
                                            }
                                        } catch (Exception e) {
//                                            e.printStackTrace();
                                            nbm_menu.setHadBottomLine(false);
                                            System.out.println("Menu xml config error:HadBottomLine(true or false)");
                                        }

                                        navbarMenus.getProfile().getNavbarMenuList().add(nbm_menu);
                                    }
                                }
                            } else if ("logout".equals(elementB_name)) {
                                Attribute attrB_href = elementB.attribute("href");
                                Attribute attrB_icon = elementB.attribute("icon");
                                Logout logout = new Logout(attrB_href.getText(), attrB_icon.getText());
                                navbarMenus.setLogout(logout);
                            }
                        }
                    }// logo/profile end
                }//navbarMenu end
            } else {
                if (elementA != null && "version".equals(elementA.getName())) {
                    this.version = elementA.attribute("value").getText();
                }
            }
        }//alice-menu end
    }

}
